package mail_remote_control;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 *
 * @author Krzysztof Lech (Stiopa)
 */
public class Terminal {
    private String cmd;
    private ArrayList comm = new ArrayList();
    public String mail = "";
    public String script = "";
    Terminal(String command){
        cmd = command;
    }

    public void commandParse(){
        StringTokenizer t = new StringTokenizer(cmd, "\n");
        int count = t.countTokens();
        cmd = "";
        for (int i=0; i < count ;i++){
            comm.add(t.nextToken());
            if (String.valueOf(comm.get(i)).toString().indexOf("<mail>") != -1){
               mail = String.valueOf(comm.get(i)).replaceAll("<mail>","");
               comm.remove(i);
               count--;
               i--;
            }else if (String.valueOf(comm.get(i)).toString().indexOf("<script>") != -1){
                script = String.valueOf(comm.get(i)).replaceAll("<script>","");
                script = script.replaceAll("\r","");
                if (script.indexOf(" ") != -1 ){
                    script = script.replaceAll(" ","");
                }
                comm.remove(i);
                count--;
                i--;
            }
        }
        comm.trimToSize();
    }

    public String doThisNow() throws IOException{
        String output = "";
        Runtime rt = Runtime.getRuntime();
        for (int i=0; i < comm.size(); i++){
            Process proc = rt.exec(String.valueOf(comm.get(i)));
            InputStream inputStream = proc.getInputStream();
                int p = 0;
                while((p = inputStream.read())>0){
                        output += ""+(char)p;
                        System.out.print(""+(char)p);
                }
        }
        return output;
    }
    
}
